import api from '../../../api/index';
import dayjs from '../../../plugin/dayjs/index';
import daysbefore from '../../../plugin/daysbefore';
import * as echarts from '../../../components/ec-canvas/echarts';

//全局声明chart
var seriesDataArr = [];
var timeArr = [];
var chart = null;

// 时间格式化
function formatTime(date = new Date()) {
	return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
}
function formatTime2(date = new Date()) {
	return dayjs(date).format('YYYY-MM-DD');
}
Page({
	/**
   * 页面的初始数据
   */
	data: {
		inputshow: false,
		inputlist: [{ unit: '血糖', value: '', text: '请输入血糖' }],
		c_val: 80,
		shebeiicon: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/sportsAdministration/xueya.png',
		fasleshebeiicon: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/sportsAdministration/gantanhao.png',
		FastingBloodSugarLast: '--',
    linedata: null,
    show: false,
    ec: {
      // 初始化图表
      onInit:  (canvas, width, height) => {
        //初始化echarts元素，绑定到全局变量，方便更改数据
        chart = echarts.init(canvas, null, {
          width: width,
          height: height
        });
        canvas.setChart(chart);
        return chart;
      }
    },
    FastingBloodSugar: '--'
	},

	/**
   * 生命周期函数--监听页面加载
   */
	onLoad(options) {
		// this.drawProgress()
		this.gethistrorylist(); //查看历史数据
    this.getloadlist(); //查询当前最新数据
  },
	gethistrorylist() {
		api
			.post('/api/hxhealth/exams/records', {
				data: {
					begindate: daysbefore.daysbefore(7),
					enddate: formatTime2(),
					everyday: true,
					itemcode: 'XYZBXY001008',
					typecode: 'glucosemeter',
					everyday: true
				}
			})
			.then((res) => {
				// console.log(res);
				console.log('----历史数据----', res);
				if (res.length > 0) {
					const jsonData = res;
					// 提取数据的数组
					const values = [];
					const times = [];

					// 遍历 body 数组
					jsonData.forEach((entry) => {
						// 遍历 devices 数组
						entry.devices.forEach((device) => {
							console.log(device);
							// 找到 code 为 "XYZBXY001007" 的项
							const item = device.items.find((item) => item.code === 'XYZBXY001008');

							// 如果找到了，将 value 和 time 添加到相应的数组中
							if (item) {
								console.log(item);
								values.push(Number(item.value)); // 将值转换为数字类型
								times.push(entry.time.slice(0, 10).replace(/-/g, '/'));
							}
						});
					});
					const linedata = {
						values,
						times
					};
          console.log(linedata);
          this.setData({
            linedata
          });
          // 模拟获取接口数据
    setTimeout(() => {
      this.getEchartData(linedata)
    }, 1000);
				}
			});
	},
	getloadlist() {
		// 整体列表查询
		api
			.post('/api/exams/lastvalues', {
				data: {
					devkind: 'glucosemeter',
					devmode: '',
					itemcode: '',
					typecode: '',
					unionuser: true
				}
			})
			.then((res) => {
				// console.log(res);
				console.log('----最新数据----', res);
				const array = res;
				for (let y = 0; y < array.length; y++) {
					if (array[y].code == 'XYZBXY001008') {
						this.setData({
							FastingBloodSugarValueLast: array[y].value
						});
					}
				}
			});
	},
	savedevices() {
		console.log('2222');
		let data = {
			name: '血糖监测',
			time: formatTime(),
			typecode: 'glucosemeter',
			typename: '血糖监测',
			devices: [
				{
					name: '血糖监测',
					kind: 'glucosemeter',
					items: [
						{
							code: 'XYZBXY001008',
							checkDate: null,
							level: null,
							value: this.data.inputlist[0].value,
							deviceBrand: '',
							deviceNo: ''
						}
					]
				}
			]
		};
		// 整体列表查询
		api
			.post('/api/hxhealth/exams/save', {
				data
			})
			.then((res) => {
				// console.log(res);
				console.log('----保存录入----', res);
				this.getloadlist();
				this.closesaveNickname();
				wx.showToast({
					icon: 'none',
					title: '保存成功'
				});
			})
			.catch((e) => {
				console.log(e);
				wx.showToast({
					icon: 'none',
					title: e.faultstring ? e.faultstring : '保存失败'
				});
			});
	},
	openNickname() {
		this.setData({
			inputshow: true
		});
	},
	closesaveNickname() {
		this.setData({
			inputshow: false
		});
	},
	userNameInput1(e) {
		console.log(e.detail.value);
		this.setData({
			'inputlist[0].value': e.detail.value
		});
	},
	saveNickname() {
		console.log(this.data.inputlist);
		this.savedevices();
	},
	modal_click_Hidden() {
		this.setData({
			inputshow: false
		});
  },
    // 绘制图表
    runColumncCanva() {
      var option = {
        title: {
          // text: '次/分', 
          textStyle: {
              fontSize: 9,
              color: '#666666'
          }
      },
        color: ['#37A2DA'],
        legend: {
          data: ['血糖变化趋势'],
          icon: 'circle',
          left: 0,
          itemWidth: 9,
          // itemStyle: {
          //     color: '#5BBF70'
          // },
          // textStyle: {
          //     color: '#333333',
          //     fontSize: 13
          // }
      },
        grid: {
          left: '0%',
          right: '3%',
          bottom: 0,
          top: '15%',
          containLabel: true,
          show: true
      },
        
        tooltip: {
          show: true,
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: timeArr,
          axisLabel:{
            rotate:45,//倾斜度 -90 至 90 默认为0
          }
        },
        yAxis: {
          type: 'value',
          splitLine: {
            lineStyle: {
              type: 'dashed'
            }
          }
        },
        series: seriesDataArr
      };
      //这里一定要做个charts是否存在的判断，因为万一ec那里没有初始化，这里就会报错
      if (chart) {
        chart.setOption(option);
        this.setData({
          show: true
        });
      }
    },
    getEchartData (linedata) {
      seriesDataArr = [{
        name: '血糖变化趋势',
        type: 'line',
        stack: 'Total',
        smooth: true,
        data: linedata.values
      }]
        timeArr = linedata.times
        this.runColumncCanva()
    },
	// 链接设备
	goBindEq() {
		wx.navigateTo({
			url: '/weightManagement/pages/check/index'
		});
	},

	/**
   * 生命周期函数--监听页面初次渲染完成
   */
	onReady: function() {
    
	},

	/**
   * 生命周期函数--监听页面显示
   */
	onShow() {},

	/**
   * 生命周期函数--监听页面隐藏
   */
	onHide() {},

	/**
   * 生命周期函数--监听页面卸载
   */
	onUnload() {},

	/**
   * 页面相关事件处理函数--监听用户下拉动作
   */
	onPullDownRefresh() {},

	/**
   * 页面上拉触底事件的处理函数
   */
	onReachBottom() {},

	/**
   * 用户点击右上角分享
   */
	onShareAppMessage() {}
});
